<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <div id="app">
      <h2>侦听器</h2>
      <p>count: {{ count }}</p>
      <button @click="count++">count++</button>

      <p>obj: {{ obj }}</p>
      <button @click="obj.age = 30">btn</button>

      <hr />

      <h2>实时地开启和关闭监听</h2>
      <p>num: {{ num }}</p>
      <button @click="num++">num++</button>
      <br />
      <button @click="start">开启监听</button>
      <br />
      <button @click="stop">停止监听</button>
    </div>

    <script src="./lib/vue3.js"></script>
    <script>
      const { createApp } = Vue;

      let unwatch;

      createApp({
        data() {
          return {
            count: 1,
            obj: {
              name: "zhangsan",
              age: 20,
            },
            num: 1,
          };
        },
        methods: {
          start() {
            unwatch = this.$watch("num", (val, oldVal) => {
              console.log(`num的值从${oldVal}变成了${val}`);
            });
          },
          stop() {
            unwatch();
          },
        },
        // 可以使用watch选项对数据进行监听
        watch: {
          // 每一个watch里面都可以接受两个参数，是val和oldVal
          count(val, oldVal) {
            setTimeout(() => {
              console.log("count被改变了", val, oldVal);
            }, 1000);
          },

          // 支持把键设置成用 . 分隔的路径
          // "obj.age"() {
          //   console.log("obj被改变了");
          // },

          // deep: true表示深度监听
          // immediate: true表示即时回调(进页面先做一次)
          // flush: "post"表示在页面更新完调用
          obj: {
            handler(val, oldVal) {
              console.log("obj改变了", val, oldVal);
            },
            deep: true,
            immediate: true,
            flush: "post",
          },
        },
      }).mount("#app");
    </script>
  </body>
</html>
